// run.js
var time = 0;
var timeout = true;
//计算距离
function getDistance(lat1, lng1, lat2, lng2) {
  var dis = 0;
  var radLat1 = toRadians(lat1);
  var radLat2 = toRadians(lat2);
  var deltaLat = radLat1 - radLat2;
  var deltaLng = toRadians(lng1) - toRadians(lng2);
  var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
  return (dis * 6378137).toFixed(2);
  function toRadians(d) { return d * Math.PI / 180; }
}
//获取计算的时间
function getTime(micro_second) {
  // 秒数
  var second = micro_second;
  // 小时位
  var hr = fill_zero_prefix( Math.floor(second / 3600));
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  return hr + ":" + min + ":" + sec + " ";
}
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    polyline: [{
      points: [],
      color: "#0000FFAA",
      width: 4,
    }],
    index:1,
    length: 0,
    _time:"00:00:00",
    km:"0.00",
    m_km:"--",
    ka:"0",
    animation:"",
    show:false,
    show_num:1,
    progress_txt: '0%', 
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLocation();
    this.setData({
      option:options.index
    })
    this.play('http://82.157.94.115:2009/static/images/start.m4a');
    setTimeout(console.log(this._time),1000)

  },
  onReady:function(){
    var that = this;
    this.drawProgressbg(); 
    this.videoPlay(this.data.km);
    this.isHide(this.data.km);

    setTimeout(this.drawCircle(this.data.km*4),1000)
    console.log(this.data.km*4)
    // this.drawCircle(1);
    // this.drawCircle(2);
  },
 
  getLocation: function () {//获取当前地址
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var site = {
          latitude: res.latitude,
          longitude: res.longitude
        }
        that.data.polyline[0].points.push(site);
        var polyline = [{
          points: that.data.polyline[0].points,
          color: "#0000FFAA",
          width: 4,
        }]
        that.data.length++;
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          polyline: polyline,
          length: that.data.length
        })
        var last = that.data.polyline[0].points[that.data.length-1];
        var first = that.data.polyline[0].points[0];
        var km = getDistance(first.latitude, first.longitude, last.latitude, last.longitude)/1000;
        if (km < 0.0015) {
          km = 0.0;
        }
        km = km.toFixed(2);
        var m_km =that.data.km!=0&&time!=0?(that.data.km/(time/10/60)).toFixed(1):'--';
        if(that.data.option == 1){
        var ka = m_km!="--"?(60*time/10/3600*(30/m_km*0.4)/1000).toFixed(1):0;
        }else{
          var ka = m_km != "--"?(m_km*60*60*1.05*time/10/3600/1000).toFixed(1):0;
        }
        that.setData({
            km:km,
            m_km:m_km,
            ka: ka,
            progress_txt:km*200+'%'
        })
      }
    })
  },
//背景圆绘制
drawProgressbg: function(){
  // 使用 wx.createContext 获取绘图上下文 context
  var ctx = wx.createCanvasContext('canvasProgressbg')
  ctx.setLineWidth(6);// 设置圆环的宽度
  ctx.setStrokeStyle('white'); // 设置圆环的颜色
  ctx.setLineCap('round') // 设置圆环端点的形状
  ctx.beginPath();//开始一个新的路径
  ctx.arc(110, 110, 100, 0, 2 * Math.PI, false);
  //设置一个原点(100,100)，半径为90的圆的路径到当前路径
  ctx.stroke();//对当前路径进行描边
  ctx.draw();
},
drawCircle: function (step){  
  var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");
    context.setLineWidth(10);
    // context.setStrokeStyle('green');
    context.setStrokeStyle(gradient); 
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    // context.arc(110, 110, 100, 0, 1 * Math.PI, false);
    context.arc(110, 110, 100, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
    context.stroke();
    context.draw()
},
  judgeTime:function(){
    if (timeout){
      time++;
      var num_time = getTime(time);
      this.setData({
        _time: num_time
      })
      if(time%10 == 0){
        this.getLocation();
      }
      setTimeout(this.judgeTime,1000);
    }else{
      return;
    }
  },
  begin:function(){

    this.setData({
      index:2
    })
    timeout = setTimeout(this.judgeTime, 1000)
  },
  stop: function () {
    this.setData({
      index: 3
    })
    timeout = false;
  },
  over:function(){
    console.log(this.data.km)
    console.log(this.data._time)
    wx.request({
      url: 'http://82.157.94.115:2005/half',
      method: 'POST',
      data: {
        "run_km": this.data.km,
        "_time": this.data._time,
        "run_speed": this.data.m_km,
        "ka": this.data.ka
      },
      success: function (res) {
        if (res.statusCode === 200) {
          console.log("成功");
          wx.navigateBack({
            delta: 1,
          })
        } else {
          console.log('failed')
        }
      }

  })
},

  continue: function () {
    this.setData({
      index: 2
    })
    timeout = true;
    timeout = setTimeout(this.judgeTime, 1000)
  },
  videoPlay:function (long){
    if(long==0.25){
      //已经完成一半了，再坚持一下~
      this.play('http://82.157.94.115:2009/static/images/half.m4a')
    }
    else if(long==0.5){
      //恭喜你已经完成此次运动，去休息一下吧
      this.play('http://82.157.94.115:2009/static/images/finish.m4a')
    }
},
play:function(src1){
  const innerAudioContext = wx.createInnerAudioContext()
  innerAudioContext.autoplay = true  // 是否自动开始播放，默认为 false
  innerAudioContext.loop =false  // 是否循环播放，默认为 false
  wx.setInnerAudioOption({ // ios在静音状态下能够正常播放音效
    obeyMuteSwitch: false,   // 是否遵循系统静音开关，默认为 true。当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音。
    success: function(e) {
      console.log(e)
      console.log('play success')
    },
    fail: function(e) {
      console.log(e)
      console.log('play fail')
    }
  })
  // innerAudioContext.src = 'http://82.157.94.115:2009/static/images/luyin.m4a';  // 音频资源的地址
  innerAudioContext.src = src1;  // 音频资源的地址
  innerAudioContext.onPlay(() => {  // 监听音频播放事件
    console.log('开始播放')
  })
  innerAudioContext.onError((res) => { // 监听音频播放错误事件
    console.log(res.errMsg)
    console.log(res.errCode)
  })
},
//跑到一半时出现鼓励
isHide:function(value){
  if(value=='0.25'){
      this.setData({
    isHide:1
  })
  }else{
    this.setData({
      isHide:0
    })
  }
}
})


 

